/**
 * 
 */
package pl.puntin.punclient.view.game;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JPanel;

import pl.puntin.punclient.controller.Controller;

/**
 * @author kakus
 *
 */
public final class GameView extends JPanel {

	private javax.swing.JTextArea ChatTextArea;
	private javax.swing.JTextArea WritingTextArea;
	private javax.swing.JButton beginGameButton;
	private javax.swing.JButton blackButton;
	private javax.swing.JButton gameViewButton;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JScrollPane jScrollPane3;
	private javax.swing.JScrollPane jScrollPane4;
	private javax.swing.JTextArea rankingTextArea;
	private javax.swing.JButton leavegameButton;
	private javax.swing.JLabel timeLabel;
	private javax.swing.JButton whiteButton;
    private javax.swing.JLabel punForDrawerLabel;

	
	private static final long INTERVAL_BETWEEN_SENDS = 1000;
	private static final long DELAY_BEFORE_FIRST_SEND = 1000;
	private static final int ROUND_TIME_IN_SECONDS = 50;
	private final Controller controller;
	private Timer timer;
	private final DrawPadComponent drawPadComponent;
	private final boolean gameCreator = false;
	private boolean imDrowing = false;
    /**
     * Creates new form GameView
     */
    public GameView(final Controller controller) {
    	this.controller = controller;
		
		drawPadComponent = new DrawPadComponent();	
		timer = new Timer(true);
        initComponents();
    }

    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        WritingTextArea = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        ChatTextArea = new javax.swing.JTextArea();
        gameViewButton = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        rankingTextArea = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        timeLabel = new javax.swing.JLabel();
        beginGameButton = new javax.swing.JButton();
        blackButton = new javax.swing.JButton();
        whiteButton = new javax.swing.JButton();
        leavegameButton = new javax.swing.JButton();
        punForDrawerLabel = new javax.swing.JLabel();


        setPreferredSize(new java.awt.Dimension(900, 700));

        drawPadComponent.setMinimumSize(new java.awt.Dimension(640, 480));

        WritingTextArea.setColumns(20);
        WritingTextArea.setRows(5);
        jScrollPane2.setViewportView(WritingTextArea);

        ChatTextArea.setColumns(20);
        ChatTextArea.setEditable(false);
        ChatTextArea.setLineWrap(true);
        ChatTextArea.setRows(5);
        jScrollPane3.setViewportView(ChatTextArea);

        gameViewButton.setText("Wyślij");
        gameViewButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
			public void actionPerformed(final java.awt.event.ActionEvent evt) {
                gameViewButtonActionPerformed(evt);
            }
        });
        /**
         * Dodaje możliwość wysyłania plików poprzez naciśnięcia enter.
         */
        WritingTextArea.addKeyListener(new keye());

        rankingTextArea.setColumns(20);
        rankingTextArea.setEditable(false);
        rankingTextArea.setLineWrap(true);
        rankingTextArea.setRows(5);
        jScrollPane4.setViewportView(rankingTextArea);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Pozostały czas do końca rundy:");

        timeLabel.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        timeLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        setTime(ROUND_TIME_IN_SECONDS);
        
        beginGameButton.setText("Rozpocznij Grę");
        beginGameButton.setVisible(true);
        beginGameButton.setEnabled(true);
		beginGameButton.addActionListener(new java.awt.event.ActionListener() {
			@Override
			public void actionPerformed(final java.awt.event.ActionEvent evt) {
				beginGameButtonActionPerformed(evt);
			}
		});
        punForDrawerLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        punForDrawerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        punForDrawerLabel.setText("Tu będą hasła");
        punForDrawerLabel.setAutoscrolls(true);

        blackButton.setBackground(new java.awt.Color(0, 0, 0));
        blackButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(final ActionEvent arg0) {
				drawPadComponent.blackPencil();
			}
		});
        whiteButton.setBackground(new java.awt.Color(255, 255, 255));
        whiteButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(final ActionEvent arg0) {
				drawPadComponent.whitePencil();
			}
		});


        leavegameButton.setText("Opuść Grę");
        leavegameButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
			public void actionPerformed(final java.awt.event.ActionEvent evt) {
                leavegameButtonActionPerformed(evt);
            }
        });
        blockComponentsForGuessers();
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(drawPadComponent, javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(gameViewButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane4)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(timeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(beginGameButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(blackButton, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(whiteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(0, 0, Short.MAX_VALUE))
                        .addComponent(leavegameButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(punForDrawerLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(blackButton, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
                                .addComponent(whiteButton, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(jLabel1)
                            .addGap(18, 18, 18)
                            .addComponent(timeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(punForDrawerLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE))
                        .addComponent(drawPadComponent, javax.swing.GroupLayout.PREFERRED_SIZE, 480, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jScrollPane3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addComponent(beginGameButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                            .addComponent(leavegameButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(47, 47, 47)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(gameViewButton, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                    .addContainerGap())
                    );
    }

    private void beginGameButtonActionPerformed(final java.awt.event.ActionEvent evt) {
        controller.gameStart();
    }

    private void leavegameButtonActionPerformed(final java.awt.event.ActionEvent evt) {
    	roundEnd();
        controller.leaveGame();
    }

    private void gameViewButtonActionPerformed(final java.awt.event.ActionEvent evt) {
    	if(imDrowing == false)
    		this.chatMessageSend();
    	else
    		controller.drawerPass();
    }
	
    public void startSendingImage()
	{
		timer.schedule(new TimerTask()
		{
			@Override
			public void run()
			{
				controller.sendImage(drawPadComponent.getBufferedImage());
			}
		}, DELAY_BEFORE_FIRST_SEND, INTERVAL_BETWEEN_SENDS);
	}

	public void displayImage(final BufferedImage bufferedImage)
	{
		drawPadComponent.setBufferedImage(bufferedImage);
		drawPadComponent.repaint();
	}
	
	
	public void buttonsUleash()
	{
		beginGameButton.setVisible(true);
		beginGameButton.setEnabled(true);
	}
	
	public void gameStarted()
	{
        beginGameButton.setVisible(false);
        beginGameButton.setEnabled(false);
        punForDrawerLabel.setVisible(false);
	}
	
	public void youCantGetTime()
	{
		timeLabel.setText("");
	}
	
	public void chatMessageSend()
	{
        String str = WritingTextArea.getText().trim();
        WritingTextArea.setText("");
		controller.sendChatMessage(str);
		WritingTextArea.requestFocus();
	}
	
	public void youAreDrowing(final String s)
	{
		imDrowing = true;
		punForDrawerLabel.setForeground(Color.red);
        punForDrawerLabel.setText(s);
        punForDrawerLabel.setVisible(true);
        whiteButton.setEnabled(true);
        blackButton.setEnabled(true); 
        WritingTextArea.setEnabled(false);
        gameViewButton.setText("Poddaj się");
        drawPadComponent.youAreDrower();
	} 
	
	private void blockComponentsForGuessers()
	{
		imDrowing = false;
        whiteButton.setEnabled(false);
        blackButton.setEnabled(false);
        punForDrawerLabel.setVisible(false);
        WritingTextArea.setEnabled(true);
        gameViewButton.setText("Wyślij");
	}

	public void showChatMessasge(final String s) {
		ChatTextArea.append(s+"\n");		
	}
	
	private void setTime(final int timeToConvert)
	{
		int i = timeToConvert, j = 0;
		if(i <60)
		{
			timeLabel.setText("0:"+i);
		}
		
		while(i >= 60)
		{
			i = i - 60;
			j++;
			if (i == 0)
			{
				timeLabel.setText(j+":00");				
			}
			else if((i < 60) && (i > 9))
				timeLabel.setText(j+":"+i);
			else if((i < 10) && (i > 0))
				timeLabel.setText(j+":0"+i);
			else
				timeLabel.setText("0:00");
		}
		
	}
	
	public void beginRound()
	{
		blockComponentsForGuessers();
		drawPadComponent.clear();
		setTime(ROUND_TIME_IN_SECONDS);
		timeCounter();
	}

	public void timeCounter()
	{		
		timer.schedule(new TimerTask()
		{
			int i = 0;
			@Override
			public void run()
			{
				i++;
				setTime(ROUND_TIME_IN_SECONDS - i);
			}
		}, DELAY_BEFORE_FIRST_SEND, DELAY_BEFORE_FIRST_SEND);
	}
	
	public void gameEnds()
	{
		roundEnd();
		buttonsUleash();
		setTime(ROUND_TIME_IN_SECONDS);
		drawPadComponent.clear();	
		blockComponentsForGuessers();
	}

	public void setRanking(final String[] names, final String[] points) {
		rankingTextArea.setText("");
		for(int i = 0; i< names.length; i++)
		{
			rankingTextArea.append(names[i]+"   "+points[i]+"\n");
		}
	}

	public void roundEnd()
	{
		timer.purge();
		timer.cancel();
		timer = new Timer();
	}
	
    private class keye extends KeyAdapter
    {
    	@Override
    	public void keyReleased(final KeyEvent ke) {
    		handleInputPressed(ke);
    	}
    	
    	private void handleInputPressed(final KeyEvent ke) {
    		
    		int a = ke.getKeyCode();
    		switch(a) {
    		case KeyEvent.VK_ENTER:
    			chatMessageSend();
    			break;
    		}
    	}
    }
}

